import { _decorator, Component, Node, Collider2D, Contact2DType, IPhysics2DContact, BoxCollider2D, PhysicsSystem2D, Prefab, instantiate, Vec3, resources, SpriteFrame, Sprite, Label, find } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('energy_control')
export class energy_control extends Component {

    @property
    speed:number = 500

    
    count = 0;//销毁的记录
    start() {

        PhysicsSystem2D.instance.enable = true;

        let collider = this.getComponent(BoxCollider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            // collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
            // collider.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
            // collider.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
        }

    }

    update(deltaTime: number) {
        let p = this.node.getPosition();

            p.y -= this.speed*deltaTime;
            if(p.y < -850){
                this.node.destroy();
            }
        this.node.setPosition(p);
    }

    onBeginContact (selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        // console.log('onBeginContact');

        if(otherCollider.tag == 2){
            return;
        }
        

        if(this.count == 0){
            this.count += 1;

            let label:Label = find("Canvas/score").getComponent(Label);
            label.string = (Number(label.string) + 1).toString();

            resources.load("enemy0_die/spriteFrame",SpriteFrame,(err,res) => {

                this.getComponent(Sprite).spriteFrame = res;//这里也会出现线程安全问题
            })
            setTimeout(() => {//此帧处理物理不能销毁，留到下一帧处理。
            // console.log(10)
            this.die()

        },300)
        }
        
        
    }

    die(){

        this.node.destroy();
    }
    // onEndContact (selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: IPhysics2DContact | null) {
    //     // 只在两个碰撞体结束接触时被调用一次
    //     console.log('onEndContact');
    // }
    // onPreSolve (selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: IPhysics2DContact | null) {
    //     // 每次将要处理碰撞体接触逻辑时被调用
    //     console.log('onPreSolve');
    // }
    // onPostSolve (selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: IPhysics2DContact | null) {
    //     // 每次处理完碰撞体接触逻辑时被调用
    //     console.log('onPostSolve');
    // }
}


